package com.seaboxdata.interfaceJob;

import com.alibaba.fastjson.JSONObject;
import com.seaboxdata.entity.HotData;
import com.seaboxdata.kafka.BaseStringKafkaProducer;
import com.seaboxdata.utils.TransRealHttpsHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Configuration
@Slf4j
public class HotDataJob {

    @Value("${real.trans.url.hotData}")
    private String url;

    @Value("${real.trans.token.hotData}")
    private String token;

    @Value("${real.trans.hotDataTopic}")
    private String topic;

    @Value("${interface.isTest}")
    private String isTest;

    @Autowired
    private BaseStringKafkaProducer baseStringKafkaProducer;

    private static final int retry = 3;

    private static int countRetry = 0;

    @Scheduled(cron = "${real.trans.hotData}")//每隔5分钟执行一次
    public void doCollect() {

        //如果是测试,直接退出
        if("true".equals(isTest)){
            return;
        }
        log.info("collect hotData begin");
        try {
            List<HotData> hotDatas = retryGetData(url, token);
            if (!CollectionUtils.isEmpty(hotDatas)) {
                //写入kafka
                Date date = new Date();
                for (HotData hotData : hotDatas) {
                    hotData.setCjsj(date);
                    baseStringKafkaProducer.sendMessageToKafka(JSONObject.toJSONString(hotData), topic);
                }
            }
        } catch (Exception e) {
            log.error("HotDataJob:write hotData error");
            e.printStackTrace();
        }
    }

    public List<HotData> retryGetData(String url, String token) {
        List<HotData> hotDatas = null;
        try {
            hotDatas = TransRealHttpsHandler.sendPost(url, token, HotData.class);
            if(hotDatas.size()==0){
                Thread.sleep(1000);
                hotDatas = retryGetData(url, token);
            }
            if ((HotData) hotDatas.get(0) != null && ((HotData) hotDatas.get(0)).getSpeed() == null) {
                if (countRetry == retry) {
                    log.error("we have try {} to getData,but still have error", countRetry);
                    return null;
                } else {
                    countRetry++;
                    Thread.sleep(1000);
                    hotDatas = retryGetData(url, token);
                }
            } else {
                countRetry = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hotDatas;
    }
}
